<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package  	PyroCMS
 * @subpackage  Categories
 * @category  	Module
 * @author  	PyroCMS Dev Team
 */
class Admin_Picture extends Admin_Controller {

	/**
	 * The current active section
	 * @access protected
	 * @var int
	 */
	protected $section = 'escort-personal';
	protected $_ci;
	var $wtm_text = "HIGHESCORTS.COM";
	/**
	 * The constructor
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
		
		$this->_ci = &get_instance();
		$this->lang->load('be_escort');
		$this->lang->load('be_escort_picture');
		$this->config->load('be_escort');
		$this->load->library('image_lib');
		$this->_path = FCPATH . $this->config->item('upload_image_path');
		$this->wtm_text = read_file("./config/wtm_text.txt");
	}
	
	/**
	 * Index method, lists all categories
	 * @access public
	 * @return void
	 */
	public function index($id)
	{
		$id OR redirect('admin/be_escort');
		
		$escort = $this->_ci->escort_entity->init('id', $id);
		$user = $this->_ci->user_entity->init('id', $escort->getUserId());
		$lockedEscort = $this->_ci->locked_escort_entity->init('escort_id', $id);
		if(!$lockedEscort){
			$this->_ci->locked_escort_entity->createNewLockedEscortEntity($id);
			$lockedEscort = $this->_ci->locked_escort_entity->init('escort_id', $id);
		}
		
		if(!$escort || !$user){
			die();
		}
		$this->data['escort'] = $escort;
		$this->data['user'] = $user;
		$this->data['lockedEscort'] = $lockedEscort;
		$this->pyrocache->delete_all('modules_m');
		$this->load->view('admin/picture/index', $this->data);
	}
	public function save(){
		$result = array();
		$result['result'] = true;
		$escortId = $this->input->post('escort_id');
		$escort = $this->_ci->escort_entity->init('id',$escortId);
		$lockedEscort = $this->_ci->locked_escort_entity->init('escort_id', $escortId);
		//$user = $this->_ci->user_entity->init('id', $userId);
		//$escort = new CI_Escort_entity();
		$escort->setSex($this->input->post('sex', TRUE));
		$escort->setPublicSex($this->input->post('public_sex', TRUE));
		$escort->setSexualOrientationId($this->input->post('sexual_orientation_id', TRUE));
		$escort->setPublicSexualOrientation($this->input->post('public_sexual_orientation', TRUE));
		$escort->setBirthDate(convertToTimeStampFromFormat($this->input->post('birth_date', TRUE),DATE_FORMAT));
		$escort->setPublicBirthDate($this->input->post('public_birth_date', TRUE));
		$escort->setLanguageIds(isset($_POST['languages']) ? implode(',', $_POST['languages']):'');
		$escort->setPublicLanguageIds($this->input->post('public_language_ids', TRUE));
		$escort->setCountryId($this->input->post('country_id', TRUE));
		$escort->setPublicCountry($this->input->post('public_country', TRUE));
		$escort->adminUpdate();

		//$lockedEscort = new CI_Locked_escort_entity();
		$lockedEscort->setLockedSex($this->input->post('locked_sex'));
		$lockedEscort->setLockedSexualOrientation($this->input->post('locked_sexual_orientation'));
		$lockedEscort->setLockedBirthDate($this->input->post('locked_birth_date'));
		$lockedEscort->setLockedLanguageIds($this->input->post('locked_language_ids'));
		$lockedEscort->setLockedCountry($this->input->post('locked_country'));
		$lockedEscort->update();
		
		$language_array_code = array_filter(explode(',',isset($_POST['languages']) ? implode(',', $_POST['languages']):''));
		foreach($language_array_code as $code){
			if(isset($_POST["language_$code"])){
				$description = $this->input->post("language_$code",TRUE);
				$escort->setDescription($description, $code, $escort->getUserId());
			}
		}
		$result['message'] = lang('escort_be_escort_picture_update_success');
		echo json_encode($result);
	}
	function re_ordering(){
		$pos = array('public_top_media'=>'public_top', 'public_medias'=>'public', 'private_medias'=>'private');
		foreach($pos as $position =>$permission){
			$value = $this->input->post($position, TRUE);
			$id_array = array_filter( explode(',', $value ));
			$i =count($id_array) + 1;
			foreach($id_array as $id){
				$MEDIA = $this->_ci->media_entity->init('id',intval($id) );
				if($MEDIA){
					$MEDIA->setOrdering($i--);
					$MEDIA->setPermission($permission);
					$MEDIA->update();
				}
			}
		}
		$result = array();
		$result['result'] = true;
		$result['message'] = lang('escort_be_escort_picture_update_success');
		echo json_encode($result);
		//echo 'ok';
	}
	function image_face_censor(){
		$value = $this->input->post('value');
		$escort_id = $this->input->post('escort_id');
		
		$USER = getAccountUserObject();
		$ESCORT = $this->_ci->escort_entity->init('id',$escort_id);
		$USER = $this->_ci->user_entity->init('id', $ESCORT->getUserId());
		$ESCORT->setImageFaceCensor($value);
		$ESCORT->update();
		$result = array();
		$result['result'] = true;
		$result['message'] = lang('escort_be_escort_picture_update_image_face_censor');
		echo json_encode($result);
		exit();
	}
	public function add($escortId)
	{
		$escort = $this->_ci->escort_entity->init('id',$escortId);
		$this->data->permissionList = array(
			'public'		=> 'Public',
			'public_top'	=> 'Public Top',
			'private'		=>	'Private'
		);
		
		if($this->input->post('add')){
			$result = array();
			$error = false;
			if(isset($_FILES['image_file'])){
				$result['file'] = true;
				$config['upload_path'] = $this->_path.$escort->getUserId();
				$config['allowed_types'] = $this->config->item('files_allowed_file_ext');
				$config['max_size']	= $this->config->item('max_size');
				$config['max_width']  = $this->config->item('max_width');
				$config['max_height']  = $this->config->item('max_height');
		
				$this->load->library('upload', $config);
		
				if ( ! $this->upload->do_upload('image_file')){
					$error = array('error' => $this->upload->display_errors());
					$result['result'] = false;
					$result['upload_path'] = $config['upload_path'];
					$result['message'] = $this->upload->display_errors();
					$error = true;
				}else{
					$data = $this->upload->data();
					$id = $this->_ci->media_entity->createNewMediaEntity();
					$media = $this->_ci->media_entity->init('id', $id);
					$sExtension = substr( $data['file_name'], ( strrpos($data['file_name'], '.') + 1 ) ) ;
					$sExtension = strtolower( $sExtension ) ;
					$type = in_array($sExtension,allowExtensionPictureUpload()) ? 'image':'video';
					
					$media->setEscortId($escort->getId());
					$media->setType($type);
					$originalFile = $this->renameMediaFileUpload($media, $data['file_name']);
					$media->setName($originalFile);
					if($type == 'image'){
						$media->setPublicTopImageBig($this->processTopBigPicture($media, $originalFile));
						$media->setPublicTopImageThin($this->processTopThinPicture($media, $originalFile));
						$media->setPublicImage($this->processPublicPicture($media, $originalFile));
					}
					$media->setOrdering($media->getCurrentOrdering($escort->getId())+1);
					$media->setClickedNo(0);
					$media->setAvatar('');
				}
			}else{
				$error = true;
				$result['result'] = false;
				$result['message'] = lang('escort_be_photo_select_file_required');
			}
			if(!$error){		
				$media->setPermission($this->input->post('permission'));
				$media->setReview($this->input->post('image_reviewed'));
				$media->setAltText($this->input->post('alt_text'));
				$media->setDescText($this->input->post('desc_text'));
				
				if(!$media->getAddPoint() && $media->getReview()){
					$media->setAddPoint(1);
					$escort = $this->_ci->escort_entity->init('id', $escortId);
					$escort->setPoint($escort->getPoint() + 10);
					$escort->update();
				} 
				$media->update();
				
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_update_photo', array($id));
				$result['result'] = true;
				$result['message'] = lang('escort_be_photo_added_success');
				//$this->session->set_flashdata('success', $this->lang->line('escort_be_photo_added_success'));
			}
			echo json_encode($result);
		}else{
			$this->template->set_layout(FALSE);
			$this->template
			->set('escort', $escort)
			->build('admin/picture/add', $this->data);
		}
	}
	public function edit($id = 0)
	{
		$this->data->permissionList = array(
			'public'		=> 'Public',
			'public_top'	=> 'Public Top',
			'private'		=>	'Private'
		);
		$id OR die();
		$media = $this->_ci->media_entity->init('id',$id);
		if($this->input->post('add')){
			$result = array();
			$error = false;
			if(isset($_FILES['image_file'])){
				$escort = $this->_ci->escort_entity->init('id',$media->getEscortId());
				$result['file'] = true;
				$config['upload_path'] = $this->_path.$escort->getUserId();
				$config['allowed_types'] = $this->config->item('files_allowed_file_ext');
				$config['max_size']	= $this->config->item('max_size');
				$config['max_width']  = $this->config->item('max_width');
				$config['max_height']  = $this->config->item('max_height');
		
				$this->load->library('upload', $config);
		
				if ( ! $this->upload->do_upload('image_file')){
					$error = array('error' => $this->upload->display_errors());
					$result['result'] = false;
					$result['upload_path'] = $config['upload_path'];
					$result['message'] = $this->upload->display_errors();
					$error = true;
				}else{
					$data = $this->upload->data();
					$originalFile = $this->renameMediaFileUpload($media, $data['file_name']);
					$media->setName($originalFile);
					$media->setPublicTopImageBig($this->processTopBigPicture($media, $originalFile));
					$media->setPublicTopImageThin($this->processTopThinPicture($media, $originalFile));
					$media->setPublicImage($this->processPublicPicture($media, $originalFile));
				}
			}
			if(!$error){		
				$media->setPermission($this->input->post('permission'));
				$media->setReview($this->input->post('image_reviewed'));
				$media->setAltText($this->input->post('alt_text'));
				$media->setDescText($this->input->post('desc_text'));
				
				if(!$media->getAddPoint() && $media->getReview()){
					$media->setAddPoint(1);
					$escort = $this->_ci->escort_entity->init('id', $media->getEscortId());
					$escort->setPoint($escort->getPoint() + 10);
					$escort->update();
					
					$POINT_LOG = $this->CI->point_log_entity->createNewEntity();
				    $POINT_LOG->setAction('ADD');
				    $POINT_LOG->setEscortId($escort->getId());
				    $POINT_LOG->setAmount(10);
				    $POINT_LOG->setCurrentPoint($escort->getPoint());
				    $POINT_LOG->setSiteRef(SITE_REF);
				    $POINT_LOG->setDescription('ADD POINT WHEN SET REVIEWED PHOTO');
				    $POINT_LOG->update();
					
				} 
				$media->update();
				
				do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_update_photo', array($id));
				$result['result'] = true;
				$result['message'] = lang('escort_be_photo_update_success');
				$this->session->set_flashdata('success', $this->lang->line('escort_be_photo_update_success'));
			}
			echo json_encode($result);
		}else{
			//$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';
			$this->template->set_layout(FALSE);
			$this->template
			->set('media', $media)
			->build('admin/picture/form', $this->data);
		}
	}
	public function delete()
	{	
		$id = $this->input->post('id');
		$result = array();
		if($this->_ci->media_entity->delete($id)){
			$result['result'] = true;
			$result['message'] = lang('escort_be_photo_delete_success');
			do_log(LOG_ACTION_BACKEND, 0, $this->_ci->ion_auth->get_user()->username, 'escort_log_delete_photo', array($id));
		}else{
			$result['result'] = false;
			$result['message'] = lang('escort_be_photo_delete_error');
		}
		echo json_encode($result);
	}
	
	private function renameMediaFileUpload( $MEDIA, $oldFile){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		
		$sExtension = strtolower ( substr( $oldFile, ( strrpos($oldFile, '.') + 1 ) ) );
		$newFile = "file_media_".$MEDIA->getId().".$sExtension";
		rename ( "./uploads/default/users/".$ESCORT->getUserId()."/".$oldFile, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		return $newFile;			
	}
	
	private function processTopBigPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_big_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
	
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		//$config['x_axis'] = '0';
		//$config['y_axis'] = '0';
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_TOP_W >= $size[0]) ? $size[0]:PUBLIC_TOP_W;
		$config['height'] = (PUBLIC_TOP_H >= $size[1]) ?$size[1]:PUBLIC_TOP_H;
		
		$this->image_lib->initialize($config);
		//$this->image_lib->crop();
		$this->image_lib->resize();
		$this->image_lib->clear();
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76)/2 );
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height'] - 76) );
				
		return $newFile;				
	}
	
	private function processTopThinPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_top_thin_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		$config['x_axis'] = '0';
		$config['y_axis'] = '0';
		//$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = FALSE;
		//$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (TOP_THIN_W >= $size[0]) ? $size[0]:TOP_THIN_W;
		$config['height'] = (TOP_THIN_H >= $size[1]) ?$size[1]:TOP_THIN_H;
		 
		
		$this->image_lib->initialize($config);
		$this->image_lib->crop();
		//$this->image_lib->resize();
		$this->image_lib->clear();
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-105);
				
		return $newFile;					
	}
	
	private function processPublicPicture($MEDIA, $originalFileName){
		$ESCORT = $this->escort_entity->init('id',$MEDIA->getEscortId());
		$sExtension = strtolower ( substr( $originalFileName, ( strrpos($originalFileName, '.') + 1 ) ) );
		$newFile = "file_media_public_".$this->digit->rand_digit(5)."_".$MEDIA->getId().".$sExtension";
		copy ( "./uploads/default/users/".$ESCORT->getUserId()."/".$originalFileName, 
					"./uploads/default/users/".$ESCORT->getUserId()."/".$newFile	);
		
		$config['source_image'] = "./uploads/default/users/".$ESCORT->getUserId()."/".$newFile;
		//$config['x_axis'] = '0';
		//$config['y_axis'] = '0';
		$config['create_thumb'] = TRUE;
		$config['maintain_ratio'] = TRUE;
		$config['thumb_marker'] = "";
		
		$size	 = getimagesize($config['source_image']);
		$config['width'] = (PUBLIC_W >= $size[0]) ? $size[0]:PUBLIC_W;
		$config['height'] = (PUBLIC_H >= $size[1]) ?$size[1]:PUBLIC_H;
		
		$this->image_lib->initialize($config);
		//$this->image_lib->crop();
		$this->image_lib->resize();
		$this->image_lib->clear();
		
		$this->wtm_center("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= ($config['height']-84)/2);
		$this->wtm_bottom_left("./uploads/default/users/".$ESCORT->getUserId()."/".$newFile, $this->wtm_text,$margin_top= $config['height']-84);
				
		return $newFile;				
	}
	
	private function wtm_center($file, $text, $margin_top= 250){
		$config['source_image'] = $file;
		$config['wm_text'] = $text;
		$config['wm_type'] = 'text';
		$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		$config['wm_font_size'] = '14';
		$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'center';
		$config['wm_hor_alignment'] = 'center';
		$config['wm_hor_offset'] = '0';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	
	private function wtm_bottom_left($file, $text, $margin_top= 500){
		$config['source_image'] = $file;
		$config['wm_overlay_path'] = './config/wtm_image.png';
		$config['wm_type'] = 'overlay';
		$congif['wm_opacity'] = 80;
		//$config['wm_font_path'] = './captcha/fonts/arial.ttf';
		//$config['wm_font_size'] = '14';
		//$config['wm_font_color'] = '#aaaaaa';
		$config['wm_vrt_alignment'] = 'top';
		$config['wm_hor_alignment'] = 'left';
		$config['wm_hor_offset'] = '50';
		$config['wm_vrt_offset'] = "$margin_top";
		$this->image_lib->initialize($config);
		$this->image_lib->watermark();	
		$this->image_lib->clear();
	}
	public function download($id = 0){
		$this->load->helper('download');
		$media = $this->_ci->media_entity->init('id',$id);
		$data = file_get_contents($media->getTargetFile());
		force_download($media->getName() , $data);
	}
}